#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <cassert>
#define DEBUG
#include "uvlog.h"

#define OWNED_FILE_NAME "owned.log"
#define MANAGED_FILE_NAME "managed.log"

namespace uv { namespace log { extern Log log; } }

void testLog();
void testLogShortcuts();

int main() {
    testLog();
    testLogShortcuts();
}

void testLog() {
    uv::log::Log *my_log = new uv::log::Log();
    my_log->openFile(OWNED_FILE_NAME, "w");
    my_log->log(uv::log::LOG_DEBUG, "tag", "Debug text...");
    my_log->log(uv::log::LOG_INFO, "tag", "Info, x = %d", 5);
    delete my_log;

    // Verify.
    char *buff;
    long f_size;
    FILE *fptr = fopen(OWNED_FILE_NAME, "r");
    assert(fptr);
    fseek(fptr, 0, SEEK_END);
    f_size = ftell(fptr);
    rewind(fptr);
    buff = new char[f_size+1];
    assert(buff);
    buff[f_size] = '\0';
    assert(fread(buff, 1, f_size, fptr) == f_size);
    assert(!std::strcmp("DEBUG tag Debug text...\nINFO tag Info, x = 5\n",
            buff));
    assert(!fclose(fptr));
    assert(!remove(OWNED_FILE_NAME));
    delete [] buff;
}

void testLogShortcuts() {
    FILE *fptr = fopen(MANAGED_FILE_NAME, "w");
    assert(fptr);
    assert(uv::log::setFile(fptr));
    uv::log::w("tag", "warning text");
    uv::log::e("tag", "Error, x = %d", 12);
    assert(uv::log::setFile(stdout));
    assert(!fclose(fptr));

    fptr = fopen(MANAGED_FILE_NAME, "r");
    assert(fptr);
    fseek(fptr, 0, SEEK_END);
    long f_size = ftell(fptr);
    rewind(fptr);
    char *buff = new char[f_size+1];
    assert(buff);
    buff[f_size] = '\0';
    assert(fread(buff, 1, f_size, fptr) == f_size);
    assert(!std::strcmp("WARNING tag warning text\nERROR tag Error, x = 12\n",
            buff));
    assert(!fclose(fptr));
    assert(!remove(MANAGED_FILE_NAME));
    delete [] buff;
}
